import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

export const LIGHT = "light";
export const DARK = "dark";
type Theme = "light" | "dark";

export interface ThemeState {
    theme: Theme;
    setTheme: (theme: Theme) => void;
    toggleTheme: () => void;
}

export const useTheme = create<ThemeState>()(
    persist(
        (set) => ({
            theme: LIGHT,
            setTheme: (theme: Theme) => {
                set({ theme });
            },
            toggleTheme: () =>
                set((state: ThemeState) => {
                    const newTheme = state.theme === LIGHT ? DARK : LIGHT;
                    return { theme: newTheme };
                }),
        }),
        {
            name: "theme",
            storage: createJSONStorage(() => localStorage),
        },
    ),
);
